package com.asset.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtil {
    private static final String signKey =
            "123456wdlhtABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
    private static final Key key = Keys.hmacShaKeyFor(signKey.getBytes());
//    private static Long tokenExpire =  1000L;
    private static Long tokenExpire = 60 * 60 * 1000 * 24L;

    public static String createToken(String userId) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);

        JwtBuilder jwtBuilder = Jwts.builder();
        jwtBuilder.claims(claims);
        jwtBuilder.signWith( key, SignatureAlgorithm.HS256); //签发算法，秘
        Date now = new Date();
        jwtBuilder.issuedAt(now); //设置当前token签发时间
        jwtBuilder.expiration(new Date(System.currentTimeMillis() + tokenExpire));
        String token = jwtBuilder.compact();
        return token;
    }

    /**
     * 验证token的合法性
     */
    public static Map<String, Object> checkToken(String token) {
        Map<String, Object> tokenPayload = null;
        try {
            // 解析并验证token
            Jws<Claims> claimsJws = (Jws<Claims>) Jwts.parser().setSigningKey(key).build().parse(token);

            // 获取payload内容
            Claims claims = claimsJws.getBody();

            // 检查token是否过期
            if (claims.getExpiration().before(new Date())) {
                throw new ExpiredJwtException(claimsJws.getHeader(), claims, "Token已过期");
            }

//            // 可以获取payload中的具体信息
//            String subject = claims.getSubject();
//            System.out.println("Token 主题: " + subject);
//
//            // 获取自定义claims
//            String userId = claims.get("userId", String.class);
//            System.out.println("用户ID: " + userId);
            tokenPayload = claims;
        } catch (MalformedJwtException e) {
            throw new RuntimeException("无效的Token格式");
        } catch (SignatureException e) {
            throw new RuntimeException("Token签名验证失败");
        } catch (ExpiredJwtException e) {
            throw new RuntimeException("Token已过期");
        } catch (UnsupportedJwtException e) {
            throw new RuntimeException("不支持的Token类型");
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("Token参数错误");
        }

//        Map<String, Object> tokenPayload = null;
//        try {
//            Jwt parse =
//                    Jwts.parser().setSigningKey(key).build().parse(token);
//            tokenPayload = (Map<String, Object>) parse.getPayload();
//        } catch (Exception e) {
//            //e.printStackTrace();
//            System.out.println("token异常");
//        }
        return tokenPayload;
    }

    public  void jwttest() throws InterruptedException {
        String token;

        token = createToken("123");
        System.out.println(token);
        Thread.currentThread().sleep(1000);
        token = createToken("123");
        System.out.println(token);
        Thread.currentThread().sleep(1000);
        token = createToken("123");
        System.out.println(token);
        Thread.currentThread().sleep(1000);
        token = createToken("43434345345");
        System.out.println(token);

        Map<String, Object> tokenPayload = checkToken(token);
        String userId = (String) tokenPayload.get("userId");
        System.out.println(userId);
    }


    //根据token来解析用户id对应的数据
    public static Integer getUserId(String token) {
        Map<String, Object> tokenPayload = checkToken(token);
        System.out.println( tokenPayload.get("userId")+"123123");
        Integer userId = (Integer.parseInt((String) tokenPayload.get("userId")));
        return userId;
    }


}